import React, { useMemo, useLayoutEffect } from 'react'
import ReactDOM from 'react-dom'
import styles from './index.module.less'

const root = document.querySelector('#modal-root')

function Mask(props) {
  const { children } = props
  return (
    <div className={styles['modal-container']}>
      <div className={styles['modal-content']}>{children}</div>
    </div>
  )
}
function Modal(props) {
  const containerEl = useMemo(() => document.createElement('div'), [])

  useLayoutEffect(() => {
    if (props.visible) {
      props?.onOpen?.()
      root?.append(containerEl)
      return () => {
        containerEl.remove()
        props?.onClose?.()
      }
    }
  }, [props.visible])

  if (props.visible) {
    return ReactDOM.createPortal(<Mask {...props} />, containerEl)
  }
  return null
}

const Index = React.memo(Modal)
export default Index
